from datetime import date, timedelta

from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from meiduo_admin.Serializers import GoodsSerializer
from users.models import User


class UserCountView(APIView):
    '''
    统计用户的总量
    '''
    def get(self, request):

        # 指定用户权限
        permission_class = [IsAdminUser]

        # 获取当前日期
        now_date = date.today()
        # 获取用户总量
        count = User.objects.all().count()
        # 返回数据
        return Response({
            "count": count,
            "date": now_date
        })


class UserDayCountView(APIView):
    '''
    获取当天增加的用户
    '''
    # 指定用户权限
    permission_class = [IsAdminUser]
    def get(self, request):
        # 获取当天时间
        now_time = date.today()
        # 获取当天增加的用户
        count = User.objects.filter(date_joined__gte=now_time).count()

        # 返回数据
        return Response({
            'count': count,
            'date': now_time
        })


class UserActiveCountView(APIView):
    '''
    获取日活跃用户
    '''
    # 添加用户权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前时间
        now_date = date.today()
        # 获取数据
        count = User.objects.filter(last_login__gte=now_date).count()
        # 返回数据
        return Response({
            'count': count,
            'date': now_date
        })

class UserOrderCountView(APIView):
    '''
    获取当天下单的用户
    '''
    # 指定用户权限
    permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前时间
        now_date = date.today()
        # 获取数据
        count = User.objects.filter(orders__create_time__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })


class UserMonthCountView(APIView):
    '''获取月增用户量'''
    # 指定用户权限
    permission_classes = [IsAdminUser]
    def get(self, request):
        # 获取当前时间
        now_date = date.today()
        # 获取上月时间
        last_date = now_date - timedelta(29)
        # 创建列表保存每天的用户量
        date_list = []

        for i in range(30):
            # 获取前一天的日期
            index_date = last_date + timedelta(days=i)
            # 获取后一天的日期
            current_date = last_date + timedelta(days=i+1)
            # 统计每天的用户新增量
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=current_date).count()
            date_list.append({
                'count': count,
                'date': index_date
            })
        return Response(date_list)

class GoodsDayView(APIView):
    '''日商品访问量'''
    # 指定用户权限
    permission_classes = [IsAdminUser]
    def get(self, request):
        # 获取当前时间
        now_date = date.today()
        # 实例化模型类
        good = GoodsVisitCount.objects.filter(date=now_date)
        # 使用序列化器获取数据
        ser = GoodsSerializer(good, many=True)
        return Response(ser.data)



